<?php
declare (strict_types=1);

namespace upload\engine;

use OSS\OssClient;
use OSS\Core\OssException;

/**
 * 阿里云存储引擎 (OSS)
 * Class Aliyun
 * @package upload\engine
 */
class Aliyun extends Base
{
    /**
     * 执行上传
     * @return array|string
     */
    public function upload(): array|string
    {
        try {
            $path = $this->path.'/'.$this->filename;
            $ossClient = new OssClient(
                $this->config['access_key_id'],
                $this->config['access_key_secret'],
                $this->config['domain'],
                true
            );
            $ossClient->uploadFile(
                $this->config['bucket'],
                $path,
                $this->file->getRealPath()
            );
        } catch (OssException $e) {
            return $e->getMessage();
        }
        return [
            'path' => $path,
            'url'  => $this->config['domain'].'/'.$path
        ];
    }

    /**
     * 删除文件
     * @param string $filePath
     * @return bool|string
     */
    public function delete(string $filePath): bool|string
    {
        try {
            $ossClient = new OssClient(
                $this->config['access_key_id'],
                $this->config['access_key_secret'],
                $this->config['domain'],
                true
            );
            $ossClient->deleteObject($this->config['bucket'], $filePath);
        } catch (OssException $e) {
            return $e->getMessage();
        }
        return true;
    }
}
